package com.security.config.filter;

import com.alibaba.fastjson.JSON;
import com.security.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component("securityFailureHandler")
public class SecurityFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure
            (HttpServletRequest req, HttpServletResponse res, AuthenticationException e)
            throws IOException, ServletException {
        res.setContentType("application/json;charset=UTF-8");
        e.printStackTrace();
        if (e instanceof BadCredentialsException){
            res.getWriter().write(JSON.toJSONString(R.error(Integer.parseInt(HttpStatus.UNAUTHORIZED.value()+""),"密码错误")));
        }
        else if (e instanceof DisabledException){
            res.getWriter().write(JSON.toJSONString(R.error(Integer.parseInt(HttpStatus.UNAUTHORIZED.value()+""),"您已被禁用，请与管理员联系")));
        }else if(e instanceof SessionAuthenticationException){
            res.getWriter().write(JSON.toJSONString(R.error(Integer.parseInt(HttpStatus.UNAUTHORIZED.value()+""),e.getMessage())));
        }
        else {
            res.getWriter().write(JSON.toJSONString(R.error(Integer.parseInt(HttpStatus.UNAUTHORIZED.value()+""),e.getMessage())));
        }
    }
}
